package com.netty.kkk.controller;

import com.alibaba.fastjson.JSONObject;
import com.netty.kkk.factory.ResultFactory;
import com.netty.kkk.service.ChatService;
import com.netty.kkk.service.UserService;
import com.netty.kkk.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.websocket.Session;
import javax.websocket.server.PathParam;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class UserInfoCrl {
    @Autowired
    private UserService userService;
    @Autowired
    private ChatService chatService;

    @CrossOrigin
    @RequestMapping(value = "/api/login", method = RequestMethod.POST, produces = "application/json; charset = UTF-8")
    @ResponseBody
    public Result login(@PathParam("username")String username, @PathParam("password") String password){
        UserInfo user = userService.login(username, password);
        if (null == user){
            return ResultFactory.buildFailResult("账户密码错误");
        }
        System.out.println(username+"登陆了");
        return ResultFactory.buildSuccessResult(user);
    }

    @CrossOrigin
    @RequestMapping(value = "/api/register", method = RequestMethod.POST, produces = "application/json; charset = UTF-8")
    @ResponseBody
    public Result login(@PathParam("username")String username, @PathParam("nickname")String nickname, @PathParam("password")String password){
        if(null != userService.findUserByName(username)){
            return ResultFactory.buildFailResult("用户名已存在");
        }

        UserInfo user = new UserInfo();
        user.setUserName(username);
        user.setNickName(nickname);
        user.setPassword(password);
        user.setFirstLetter(nickname.substring(0,1));
        userService.register(user);
        System.out.println(username+"注册了");
        return ResultFactory.buildSuccessResult(user);
    }

    /**
     * 用户登录后返回 用户所有的频道
     * @param userName
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/api/userChannels", method = RequestMethod.GET, produces = "application/json; charset = UTF-8")
    @ResponseBody
    public Result userChannels(@PathParam("userName")String userName){
        List<ChatInfo> chatInfoList = chatService.getUserChatList(userName);
        return ResultFactory.buildSuccessResult(chatInfoList);
    }

    @CrossOrigin
    @RequestMapping(value = "/api/getUserById", method = RequestMethod.GET, produces = "application/json; charset = UTF-8")
    @ResponseBody
    public Result getUserById(@PathParam("userName")String userId){
        UserInfo userInfo = userService.findUserByName(userId);
        return ResultFactory.buildSuccessResult(userInfo);
    }

    @CrossOrigin
    @RequestMapping(value = "/api/getChatById", method = RequestMethod.GET, produces = "application/json; charset = UTF-8")
    @ResponseBody
        public Result getChatById(@PathParam("chatId")String chatId){
        ChatInfo chatInfo = chatService.getChatInfoById(chatId);
        return ResultFactory.buildSuccessResult(chatInfo);
    }

    @CrossOrigin
    @RequestMapping(value = "/api/getChatMemberById", method = RequestMethod.GET, produces = "application/json; charset = UTF-8")
    @ResponseBody
    public Result getChatMemberById(@PathParam("chatId")String chatId){
        List<UserInfo> members = chatService.getMemberById(chatId);
        return ResultFactory.buildSuccessResult(members);
    }

    @CrossOrigin
    @RequestMapping(value = "/api/getMsgRecorder", method = RequestMethod.GET, produces = "application/json; charset = UTF-8")
    @ResponseBody
    public Result getMsgRecorder(@PathParam("chatId")String chatId, @PathParam("times")int times){
        List<MessageRecord> messageRecordList = chatService.getMsgRecorder(chatId, times, 10);
        System.out.println(chatId+"请求历史记录");
        return ResultFactory.buildSuccessResult(messageRecordList);
    }

    @CrossOrigin
    @RequestMapping(value = "/api/getAllUser", method = RequestMethod.GET, produces = "application/json; charset = UTF-8")
    @ResponseBody
    public Result getAllUser(@PathParam("userName")String userName){
        List<UserInfo> userInfosList = userService.getAllUser(userName);
        System.out.println(userInfosList);
        return ResultFactory.buildSuccessResult(userInfosList);
    }

    @CrossOrigin
    @RequestMapping(value = "/api/changeUserInfo", method = RequestMethod.POST, produces = "application/json; charset = UTF-8")
    @ResponseBody
    public Result changeUserInfo(@RequestBody UserInfo userInfo){
        userInfo.setFirstLetter(userInfo.getNickName().substring(0,1));
        userService.changeUserInfo(userInfo);
        WebsocketUserCrl websocketUserCrl = new WebsocketUserCrl();
        websocketUserCrl.changeUserInfoMsg(userInfo);
        List<ChatInfo> userChatList = chatService.getUserChatList(userInfo.getUserName());
        ConcurrentHashMap<String, List<Session>> groupMemberMap = WebsocketGroupCrl.groupMemberMap;
        ConcurrentHashMap<String, Map<String, UserInfo>> onLineUserMap = WebsocketGroupCrl.onLineUserMap;
        for (ChatInfo chatInfo : userChatList){
            MessageIndex messageIndex = new MessageIndex();
            messageIndex.setMessageType(8);
            messageIndex.setMessage(userInfo);
            if (onLineUserMap.containsKey(String.valueOf(chatInfo.getChatId()))){
                Map<String, UserInfo> map = onLineUserMap.get(String.valueOf(chatInfo.getChatId()));
                map.put(userInfo.getUserName(),userService.findUserByName(userInfo.getUserName()));
            }
            if (groupMemberMap.containsKey(String.valueOf(chatInfo.getChatId()))){
                try{
                    for (Session session : groupMemberMap.get(String.valueOf(chatInfo.getChatId()))){
                        String text = JSONObject.toJSONString(messageIndex);
                        session.getBasicRemote().sendText(text);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return ResultFactory.buildSuccessResult("信息修改成功");
    }

//    @CrossOrigin
//    @RequestMapping(value = "/api/changeUserInfoTest", method = RequestMethod.POST, produces = "application/json; charset = UTF-8")
//    @ResponseBody
//    public Result changeUserInfoTest(@RequestParam("userName") String userName, @RequestParam("nickName") String nickName, @RequestParam("file") MultipartFile file){
//        String fullFileName = "";
//        if (!file.isEmpty()) {
//            // 获取文件名
//            String fileName = file.getOriginalFilename();
//            // 获取文件的后缀名
//            String suffixName = fileName.substring(fileName.lastIndexOf("."));
//            fileName = String.valueOf(System.currentTimeMillis())+suffixName;
//            // 文件上传路径
//            String filePath = "d:/pic/";
//            // 解决中文问题,liunx 下中文路径,图片显示问题
//            //fileName = UUID.randomUUID() + suffixName;
//            fullFileName = filePath + fileName;
//            File dest = new File(fullFileName);
//            // 检测是否存在目录
//            if (!dest.getParentFile().exists()) {
//                dest.getParentFile().mkdirs();
//            }
//            try {
//                file.transferTo(dest);
//            } catch (IllegalStateException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//
//        UserInfo userInfo = new UserInfo();
//        userInfo.setUserName(userName);
//        userInfo.setAvatarUrl(fullFileName);
//        userInfo.setFirstLetter(nickName.substring(0,1));
//        userService.changeUserInfo(userInfo);
//        WebsocketUserCrl websocketUserCrl = new WebsocketUserCrl();
//        websocketUserCrl.changeUserInfoMsg(userInfo);
//        List<ChatInfo> userChatList = chatService.getUserChatList(userInfo.getUserName());
//        ConcurrentHashMap<String, List<Session>> groupMemberMap = WebsocketGroupCrl.groupMemberMap;
//        ConcurrentHashMap<String, Map<String, UserInfo>> onLineUserMap = WebsocketGroupCrl.onLineUserMap;
//        for (ChatInfo chatInfo : userChatList){
//            MessageIndex messageIndex = new MessageIndex();
//            messageIndex.setMessageType(8);
//            messageIndex.setMessage(userInfo);
//            if (onLineUserMap.containsKey(String.valueOf(chatInfo.getChatId()))){
//                Map<String, UserInfo> map = onLineUserMap.get(String.valueOf(chatInfo.getChatId()));
//                map.put(userInfo.getUserName(),userService.findUserByName(userInfo.getUserName()));
//            }
//            if (groupMemberMap.containsKey(String.valueOf(chatInfo.getChatId()))){
//                try{
//                    for (Session session : groupMemberMap.get(String.valueOf(chatInfo.getChatId()))){
//                        String text = JSONObject.toJSONString(messageIndex);
//                        session.getBasicRemote().sendText(text);
//                    }
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//            }
//        }
//
//        return ResultFactory.buildSuccessResult("信息修改成功");
//    }

}
